package com.atguigu.day06;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class Flink09_Timer_Process_Exec_WithKeyedState {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.将数据转为JavaBean
        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });

        //4.将相同id的数据聚和到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = map.keyBy("id");

        //TODO 5.需求逻辑处理
        /**
         * 监控水位传感器的水位值，
         * 如果水位值在五秒钟之内（创建一个5秒的定时器）
         * 连续上升（要保存上一次的水位，拿着当前水位去对比，如果没上升则删除定时器），
         * 则报警（报警之后继续创建定时器），
         * 并将报警信息输出到侧输出流。
         */
        SingleOutputStreamOperator<String> result = keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {
            //定义变量用来保存上一次水位
//            private Integer lastVc = Integer.MIN_VALUE;
            private ValueState<Integer> lastVc;

            //定义变量用来保存定时器时间
//            private Long timer = Long.MIN_VALUE;
            private ValueState<Long> timer;

            @Override
            public void open(Configuration parameters) throws Exception {
                lastVc = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("lastVc", Integer.class,Integer.MIN_VALUE));

                timer = getRuntimeContext().getState(new ValueStateDescriptor<Long>("timer", Long.class));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                //判断水位是否上升
                if (value.getVc() > lastVc.value()) {
                    //注册定时器
                    if (timer.value() == null) {
                        //定时器没有被注册
                        timer.update(ctx.timerService().currentProcessingTime() + 5000);
                        System.out.println("注册定时器:"+ctx.getCurrentKey()+":"+timer.value());
                        ctx.timerService().registerProcessingTimeTimer(timer.value());
                    }
                } else {
                    //水位没有上升
                    //删除定时器
                    System.out.println("删除定时器:"+ctx.getCurrentKey()+":" + timer.value());
                    ctx.timerService().deleteProcessingTimeTimer(timer.value());
                    timer.clear();
                }

                //将当前水位保存起来
                lastVc.update(value.getVc());
                out.collect(value.toString());
            }

            /**
             * 定时器触发的逻辑
             *
             * @param timestamp
             * @param ctx
             * @param out
             * @throws Exception
             */
            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                //水位5秒钟连续上升
                ctx.output(new OutputTag<String>("output") {
                }, "警报！！！水位5s连续上升！！");

                //重置定时器时间
               timer.clear();

            }
        });

        result.print();

        result.getSideOutput(new OutputTag<String>("output") {
        }).print();

        env.execute();
    }
}
